<?php
    include_once("checkAuthenticationAction.php");
    include_once("../service/categoryService.php");
    $title = $_POST["categoryTitle"];
    $parent = ($_POST["parent_category"] == "" ? 0 : $_POST["parent_category"]);
	$attributes = isset($_POST["selectedAtts"])?$_POST["selectedAtts"]:array();
	$options = isset($_POST["selectedOpts"])?$_POST["selectedOpts"]:array();	
    $order = ($_POST["categoryOrder"] == "" ? 0 : $_POST["categoryOrder"]);
    if(createCategory($title, $parent,$order)){
        $newCateId = mysql_insert_id();
        //echo "new Cate Id:". $newCateId."<br/>";
		//Insert Attribute
        for($i = 0; $i < count($attributes); $i++){
            //echo "attrid:".$attributes[$i]."<br/>";
            //echo "is int:".is_numeric($attributes[$i])."<br/>";
            if(is_numeric($attributes[$i]) == 1){
                assignAttToCate($newCateId,$attributes[$i]); 
            }else{
                createAttribute($attributes[$i]);
                $newAttId = mysql_insert_id();
                //echo "new Att Id:".$newAttId."<br/>";
                assignAttToCate($newCateId,$newAttId);             
            }
        }
		//Insert Option
		for($i = 0; $i < count($options); $i++){
            //echo "optid:".$options[$i]."<br/>";
            //echo "is int:".is_numeric($options[$i])."<br/>";
            
            
            if(is_numeric($options[$i]) == 1){
                assignOptToCate($newCateId,$options[$i]); 
            }else{
                createOption($options[$i]);
                $newOptId = mysql_insert_id();
                //echo "new Opt Id:".$newOptId."<br/>";
                assignOptToCate($newCateId,$newOptId);             
            }
        }
    }
	echo "<script>window.location.href='../admin/category.php';</script>";
    
?>
